package com.admin.system.config;

import cn.hutool.core.date.DateTime;
import com.admin.common.constant.Constant;
import com.admin.oauth.util.LoginUserUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * @author sq-lan
 **/
@Component
public class MyBatisMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_BY = "createBy";
    private static final String UPDATE_BY = "updateBy";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        Timestamp timestamp = DateTime.now().toTimestamp();
        this.setFieldValByName(CREATE_TIME, timestamp, metaObject);
        this.setFieldValByName(UPDATE_TIME, timestamp, metaObject);

        if (metaObject.hasGetter(CREATE_BY) || metaObject.hasGetter(UPDATE_BY)) {
            int userId = Constant.SYSTEM_ID;
            try {
                // 操作人
                userId = LoginUserUtil.userId();
            } catch (Exception e) {
                // 忽略
            }
            this.setFieldValByName(CREATE_BY, userId, metaObject);
            this.setFieldValByName(UPDATE_BY, userId, metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 修改时间
        this.setFieldValByName(UPDATE_TIME, DateTime.now().toTimestamp(), metaObject);
        if (metaObject.hasGetter(UPDATE_BY)) {
            int userId = Constant.SYSTEM_ID;
            try {
                userId = LoginUserUtil.userId();
            } catch (Exception e) {
                //
            }
            this.setFieldValByName(UPDATE_BY, userId, metaObject);
        }
    }
}

